import React, { Component, createRef } from 'react';
import { Breadcrumb, PageHeader, Button, Table, Tag, Space, Pagination, Modal, Form, Input, Select, message } from "antd";
import CheckLogin from "../../../hoc/CheckLogin"
import url from "../../../config/url"
import req from "../../../http/req"
const { Option } = Select
const { confirm } = Modal;
class Index extends Component {
  formRef = createRef();
  constructor(props) {
    super(props);
    // 表格列声明
    this.columns = [
      {
        title: '序号', //表头的列名称
        dataIndex: 'id', //待显示数据源的字段名称（务必注意大小写）
        key: 'id', //与以前一样，必须要有，且唯一
        //数据加工处理函数，函数返回需要渲染的内容。形参1：当前字段对应的数据，形参2：当前字段所在行的整条数据
        // render: text => <a>{text}</a>,
      },
      {
        title: '用户名',
        dataIndex: 'username',
        key: 'username',
      },
      {
        title: '手机号',
        dataIndex: 'mobile',
        key: 'mobile',
      },
      {
        title: '邮箱',
        key: 'email',
        dataIndex: 'email',
        render: (text) => <a href={"mailto:" + text}>{text}</a>,
      },
      {
        title: '性别',
        key: 'gender',
        dataIndex: 'gender',
        render: (text) => {
          if (text === '1') {
            return <Tag color="blue">男</Tag>
          }
          if (text === '2') {
            return <Tag color="red">女</Tag>
          }
          if (text === '3') {
            return <Tag color="black">保密</Tag>
          }
        },
      },
      {
        title: '状态',
        key: 'status',
        dataIndex: 'status',
        render: (text) => {
          if (text === '1') {
            return <Tag color="green">正常</Tag>
          }
          if (text === '2') {
            return <Tag color="red">禁用</Tag>
          }
        },
      },
      {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <Space size="middle">
            <a onClick={() => this.edit(record)}>编辑</a>
            <a onClick={() => this.handleDelete(record.id)}>删除</a>
          </Space>
        ),
      },
    ];
    this.state = {
      page: 1,
      total: 0,
      pageSize: 10,
      current: 1,
      loading: false,
      visible: false,
    };
  }
  bread = JSON.parse(sessionStorage.getItem("bread"))
  render() {
    const { visible, loading } = this.state
    let pathname = this.props.location.pathname
    let crumb = []
    this.bread.forEach(el => {
      if(pathname === el.auth_path) {
        crumb = el.auth_bread.split(",")
      }
    })
    return (
      <>
        {/* 面包屑 */}
        <Breadcrumb>
          {/* acl的auth_bread */}
          {
            crumb.map(el => {
              return <Breadcrumb.Item key={el}>{el}</Breadcrumb.Item>
            })
          }
        </Breadcrumb>
        {/* 页头 */}
        <PageHeader
          ghost={false}
          onBack={() => window.history.back()}
          title="用户列表"
          extra={[
            <Button key="btn_add" type="primary" onClick={this.addUser.bind(this)}>
              用户添加
            </Button>,
          ]}
        >
        </PageHeader>
        <Modal
          visible={visible}
          title="添加用户"
          centered
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          footer={[
            <Button key="back" onClick={this.handleCancel}>
              取消
            </Button>,
          ]}
          forceRender={true}
        >
          <Form
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            onFinish={this.onFinish.bind(this)}
            onFinishFailed={this.onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="用户名"
              name="username"
              rules={[{ required: true, message: 'Please input your username!' }]}
            >
              <Input placeholder="用户名" />
            </Form.Item>
            <Form.Item
              label="手机号"
              name="mobile"
              rules={[{ required: true, message: 'Please input your mobile!' }]}
            >
              <Input placeholder="手机号" />
            </Form.Item>
            <Form.Item
              label="邮箱"
              name="email"
              rules={[{ required: true, message: 'Please input your email!' }]}
            >
              <Input placeholder="邮箱" />
            </Form.Item>
            <Form.Item
              label="密码"
              name="password"
              rules={[{ required: true, message: 'Please input your password!' }]}
            >
              <Input placeholder="密码" />
            </Form.Item>
            <Form.Item
              label="性别"
              name="gender"
              rules={[{ message: 'Please input your gender!' }]}
            >
              <Select
                placeholder="选择性别"
                // onChange={this.onGenderChange}
                allowClear
              >
                <Option value="1">男</Option>
                <Option value="2">女</Option>
                <Option value="3">保密</Option>
              </Select>
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                添加
              </Button>
            </Form.Item>
          </Form>
        </Modal>
        <Modal
          visible={loading}
          title="编辑用户"
          centered
          onOk={this.handleOk}
          onCancel={this.handleCancel}
          footer={[
            <Button key="back" onClick={this.handleCancel}>
              取消
            </Button>,
          ]}
          forceRender={true}
        >
          <Form
            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            onFinish={this.onFinish1.bind(this)}
            onFinishFailed={this.onFinishFailed}
            autoComplete="off"
            ref={this.formRef}
          >
            <Form.Item
              label="用户名"
              name="username"
              rules={[{ required: true, message: 'Please input your username!' }]}
            >
              <Input placeholder="用户名" />
            </Form.Item>
            <Form.Item
              label="手机号"
              name="mobile"
              rules={[{ required: true, message: 'Please input your mobile!' }]}
            >
              <Input placeholder="手机号" />
            </Form.Item>
            <Form.Item
              label="邮箱"
              name="email"
              rules={[{ required: true, message: 'Please input your email!' }]}
            >
              <Input placeholder="邮箱" />
            </Form.Item>
            <Form.Item
              label="密码"
              name="password"
              rules={[{ message: 'Please input your password!' }]}
            >
              <Input placeholder="密码" />
            </Form.Item>
            <Form.Item
              label="性别"
              name="gender"
              rules={[{ message: 'Please input your gender!' }]}
            >
              <Select
                placeholder="选择性别"
                // onChange={this.onGenderChange}
                allowClear
              >
                <Option value="1">男</Option>
                <Option value="2">女</Option>
                <Option value="3">保密</Option>
              </Select>
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
              <Button type="primary" htmlType="submit">
                编辑
              </Button>
            </Form.Item>
          </Form>
        </Modal>
        {/* 表格
          (表格需要加rowKey属性来生成行的key，否则报错)
          （scroll属性：加滚动条）
        */}
        {/* data(数据源可变)放到state中 */}
        <Table dataSource={this.state.data} rowKey={(record) => record.id} columns={this.columns} pageination={false}/>
        {/* 分页器 */}
        <div style={{ textAlign: "center", marginTop: "25px" }}>
          <Pagination
            defaultCurrent={this.state.page}
            current={this.state.current}
            total={this.state.total}
            onChange={this.loadData}
          />
        </div>
      </>
    );
  }
  // 添加用户
  addUser() {
    this.setState({
      visible: true,
    })
  }
  onFinish(values) {
    values.gender = values.gender - 0
    console.log(values)
    req.post(`https://reactapi.iynn.cn/api/users/add`, values).then((res) => {
      this.loadData()
    })
    // req.put(`https://reactapi.iynn.cn/api/users/${record.id}`,values)
  }
  onFinishFailed(errorInfo) {
    console.log(errorInfo)
  }
  handleOk = () => {
    this.setState({ loading: true });
    setTimeout(() => {
      this.setState({ loading: false, visible: false });
    }, 3000);
  };

  handleCancel = () => {
    this.setState({ visible: false });
  };
  handleDelete = (key) => {
    confirm({
      title: '确定删除?',
      onOk:()=>{
        req.delete(`https://reactapi.iynn.cn/api/users/${key}`).then((res) => {
          message.success("删除成功")
          this.loadData()
        })
      }
    });
  };
  edit(record){
    this.setState({
      loading: true,
    })
    // 回显数据
    req.get(`https://reactapi.iynn.cn/api/users/${record.id}`).then((res) => {
      let info = res.data.userInfo
      this.formRef.current.setFieldsValue({
        username: info.username,
        gender: info.gender,
        email: info.email,
        password: info.password,
        mobile: info.mobile
      });
    })
    window.sessionStorage.setItem("id",record.id)
  }
  onFinish1(values) {
    values.gender = values.gender - 0
    console.log(values)
    let id = window.sessionStorage.getItem("id")
    console.log(id)
    req.put(`https://reactapi.iynn.cn/api/users/${id}`, values).then((res) => {
      console.log(res.data)
      this.loadData()
    })
    this.setState({
      loading: false,
    })
    // req.put(`https://reactapi.iynn.cn/api/users/${record.id}`,values)
  }
  componentDidMount() {
    this.loadData(this.state.page)
  }
  // 加载数据
  loadData = (page) => {
    req.get(url.GetUsers, {
      params: {
        page,
      }
    }).then(res => {
      if(res.data.errNo === 0) {
        this.setState({
          data: res.data.paginate.data,
          total: res.data.paginate.total,
          current: page
        })
      }
    })
  }
}

export default CheckLogin(Index);
